﻿using AutoMapper;
using QYmall.Core.Common.Emum;
using QYmall.Core.Common.Extensions;
using QYmall.Core.Common.Helper;
using QYmall.Core.DBFactory.Database;
using QYmall.Core.IServices;
using QYmall.Core.Model.Models;
using QYmall.Core.Model.ViewModels;
using Microsoft.AspNetCore.Http;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using System.Threading.Tasks;

namespace QYmall.Core.Services
{
    /// <summary>
    /// 商户资金日志接口实现
    /// </summary>
    public class MerchantAmountLogService : BaseService, IMerchantAmountLogService
    {
        private readonly IMapper _mapper;
        public MerchantAmountLogService(IMapper mapper, IDbContextFactory contentFactory) : base(contentFactory)
        {
            _mapper = mapper;
        }

        /// <summary>
        /// 查询一条记录
        /// </summary>
        public async Task<MerchantAmountLog?> QueryAsync(Expression<Func<MerchantAmountLog, bool>> funcWhere, WriteRoRead writeAndRead = WriteRoRead.Read)
        {
            _context = _contextFactory.CreateContext(writeAndRead);//连接数据库

            var result = await _context.Set<MerchantAmountLog>()
                .Include(x => x.Merchant)
                .FirstOrDefaultAsync(funcWhere);
            return result;
        }

        /// <summary>
        /// 查询指定数量列表
        /// </summary>
        public async Task<IEnumerable<MerchantAmountLog>> QueryListAsync(int top, Expression<Func<MerchantAmountLog, bool>> funcWhere,
            string orderBy, WriteRoRead writeAndRead = WriteRoRead.Read)
        {
            _context = _contextFactory.CreateContext(writeAndRead);//连接数据库

            var result = _context.Set<MerchantAmountLog>()
                .Include(x => x.Merchant)
                .Where(funcWhere).OrderByBatch(orderBy);//调用Linq扩展类进行排序
            if (top > 0) result = result.Take(top);//等于0显示所有数据
            return await result.ToListAsync();
        }

        /// <summary>
        /// 查询分页列表
        /// </summary>
        public async Task<PaginationList<MerchantAmountLog>> QueryPageAsync(int pageSize, int pageIndex, Expression<Func<MerchantAmountLog, bool>> funcWhere,
            string orderBy, WriteRoRead writeAndRead = WriteRoRead.Read)
        {
            _context = _contextFactory.CreateContext(writeAndRead);//连接数据库

            var result = _context.Set<MerchantAmountLog>()
                .Include(x => x.Merchant)
                .Where(funcWhere).OrderByBatch(orderBy);//调用Linq扩展类排序
            return await PaginationList<MerchantAmountLog>.CreateAsync(pageIndex, pageSize, result);
        }

        /// <summary>
        /// 添加记录
        /// </summary>
        public async Task<MerchantAmountLog> AddAsync(MerchantAmountLogEditDto modelDto, WriteRoRead writeAndRead = WriteRoRead.Write)
        {
            _context = _contextFactory.CreateContext(writeAndRead);//连接数据库

            //检查是否有足够的可用余额=余额-不可用余额
            var merchantModel = await _context.Set<Merchants>().FirstOrDefaultAsync(x => x.Id == modelDto.MerchantId && x.IsLock == 0);
            if (merchantModel == null)
            {
                throw new ResponseException("商户不存在或被禁用");
            }
            //检查提现金额是否正确
            if (modelDto.Amount == 0)
            {
                throw new ResponseException("金额必须是正数或负数");
            }

            //映射实体
            var model = _mapper.Map<MerchantAmountLog>(modelDto);
            model.AddTime = DateTime.Now;
            //金额负数
            if (modelDto.Amount < 0)
            {
                var balanceAmount = merchantModel.Amount - merchantModel.FrozenAmount;
                if (balanceAmount <= 0 || balanceAmount < modelDto.Amount * -1)
                {
                    throw new ResponseException("商户可用余额不足，无法扣取");
                }
            }
            merchantModel.Amount += modelDto.Amount;
            //保存数据
            _context.Set<Merchants>().Update(merchantModel);//修改商户余额
            await _context.Set<MerchantAmountLog>().AddAsync(model);
            var result = await this.SaveAsync();
            if (!result)
            {
                throw new ResponseException("数据保存时发生意外错误");
            }
            return model;
        }


    }
}
